import express from 'express';
import { authenticateToken, isAdmin } from '../middleware/auth.js';
import Movie from '../models/Movie.js';
import Order from '../models/Order.js';

const router = express.Router();

// 获取所有电影
router.get('/', async (req, res) => {
  try {
    const movies = await Movie.find();
    res.json(movies);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取电影详情
router.get('/:id', async (req, res) => {
  try {
    const movie = await Movie.findById(req.params.id);
    if (!movie) {
      return res.status(404).json({ message: '电影不存在' });
    }
    res.json(movie);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建电影
router.post('/', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { title, description, totalTickets, price, showtime } = req.body;
    const movie = new Movie({
      title,
      description,
      totalTickets,
      remainingTickets: totalTickets,
      price,
      showtime
    });
    await movie.save();
    res.status(201).json(movie);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新电影信息
router.put('/:id', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { title, description, totalTickets, price, showtime } = req.body;
    const movie = await Movie.findById(req.params.id);

    if (!movie) {
      return res.status(404).json({ message: '电影不存在' });
    }

    // 更新电影信息
    movie.title = title;
    movie.description = description;
    movie.totalTickets = totalTickets;
    movie.price = price;
    movie.showtime = showtime;

    // 如果总票数增加，相应增加剩余票数
    const ticketDifference = totalTickets - movie._doc.totalTickets;
    if (ticketDifference > 0) {
      movie.remainingTickets += ticketDifference;
    }

    await movie.save();
    res.json(movie);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取电影订单列表（仅管理员可访问）
router.get('/:id/orders', authenticateToken, isAdmin, async (req, res) => {
  try {
    const movieId = req.params.id;
    const orders = await Order.find({ movieId })
      .populate('userId', 'username')
      .populate('movieId', 'title showtime price');

    // 格式化返回数据
    const formattedOrders = orders.map(order => ({
      _id: order._id,
      username: order.userId.username,
      quantity: order.quantity,
      totalPrice: order.totalPrice,
      status: order.status,
      createdAt: order.createdAt,
      movie: {
        title: order.movieId.title,
        showtime: order.movieId.showtime,
        price: order.movieId.price
      }
    }));

    res.json(formattedOrders);
  } catch (error) {
    console.error('获取电影订单列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

export default router;